package com.tledu.httpclient;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.swing.text.html.parser.Entity;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class HttpClient3 {
    public static void main(String[] args) throws IOException {
        // get 、 post 、 put 、delete 、  options
        // 接口文档
        //      接口地址，请求方式，请求的参数，请求体的类型
        String url = "http://1.117.81.216/test/post";
        // 1. 创建HttpCLient
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 2. 构建请求
        HttpPost httpPost = new HttpPost(url);
        // 2.1 构建post请求，post请求是有请求体的，携带请求体
        //      封装参数
        List<NameValuePair> pairList = new ArrayList<>();
        pairList.add(new BasicNameValuePair("name","cyrus"));
        pairList.add(new BasicNameValuePair("hobby","打篮球"));
        //     构建请求体，Content-Type:multipart/form-data，一般是文件上传
        //     构建请求体，Content-Type:application/json，对应的是json的请求
        //     构建请求体，Content-Type:application/x-www-form-urlencoded，对应的是表单的请求
        // 构建了表单请求的请求体
       UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairList, "utf8");
       httpPost.setEntity(entity);
        // 3. 发送请求
        CloseableHttpResponse response = httpClient.execute(httpPost);
        // 4. 拿到结果
        int code = response.getStatusLine().getStatusCode();
        if (code != 200) {
            httpPost.abort();
            System.out.println("出错了");
        }else {
            // 获取请求体
            HttpEntity entity1 = response.getEntity();
            System.out.println(EntityUtils.toString(entity1));
            EntityUtils.consume(entity1);
            response.close();
        }

    }
}
